package priv.wangy.micro.common.utils;

import org.apache.commons.lang3.StringUtils;
import priv.wangy.micro.common.utils.secret.AesUtil;

/**
 *@author wangy
 *@since 2024/9/11
 */
public class EncryptUtil {

    private final static String ENCRYPT_FORMAT = "%s-%s-%s";
    private final static String DECRYPT_FORMAT = "%s%s%s";

    /**
     * 加密
     * @author wangy
     * @since 11:05 2024/9/11
     * @param plainText
     * @param type
     * @return java.lang.String
     **/
    public static String encrypt(String plainText, EncryptType type) {
        switch (type) {
            // 手机号脱敏
            case MOBILE_PHONE, ID_CARD -> {
                return EncryptUtil.encrypt(plainText, 3, 4);
            }
            default -> {
                return EncryptUtil.encrypt(plainText, 0, 0);
            }
        }
    }

    /**
     * 明文加密
     * @author wangy
     * @since 9:22 2024/9/11
     * @param plainText
     * @param start
     * @param end
     * @return java.lang.String
     **/
    public static String encrypt(String plainText, int start, int end) {
        if (StringUtils.isEmpty(plainText)) {
            return plainText;
        }
        // 传值有误时，按不截取加密
        if (start < 0 || end < 0 || end > plainText.length() || start >= end) {
            return AesUtil.encrypt(plainText);
        }
        String header = plainText.substring(0, start);
        String bottom = plainText.substring(plainText.length() - end);
        String center = plainText.substring(start, plainText.length() - end);
        return String.format(ENCRYPT_FORMAT, AesUtil.encrypt(center), header, bottom);
    }

//    public static void main(String[] args) {
//        String encryptStr = encrypt("13339730195", 3, 4);
//        System.out.println(encryptStr);
//        String deStr = decrypt(encryptStr);
//        System.out.println(deStr);
//    }

    public static String decrypt(String encryptStr) {
        if (StringUtils.isEmpty(encryptStr)) {
            return encryptStr;
        }
        String[] strList = encryptStr.split("-");
        if (strList.length != 3) {
            return AesUtil.decrypt(encryptStr);
        }
        return String.format(DECRYPT_FORMAT, strList[1], AesUtil.decrypt(strList[0]), strList[2]);
    }
}
